package com.jackrain.clouddata.oms.dao;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.core.db.Tools;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.web.query.QueryEngine;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import static com.jackrain.clouddata.oms.util.KeyValueUtils.keyAppend;
import static com.jackrain.clouddata.oms.util.KeyValueUtils.valueAppend;

/**
 * Created by nathan on 2017/8/15.
 */
@Component
public class RetailDao {

    @Transactional
    public void execute(JSONObject mainJson, JSONArray itemArray,Long clientId) {

        String countSql = "SELECT COUNT(*) FROM M_RETAIL WHERE AD_CLIENT_ID = ? AND BILLNO = ?";
        int count = QueryEngine.getInstance().doQueryInt(countSql, new Object[]{clientId, mainJson.getString("BILLNO")});
        if (count == 0) {
            for (int i = 0; i < itemArray.size(); i++) {
                JSONObject itemJson = itemArray.getJSONObject(i);
                //获取子表名称
                String itemName = itemJson.getString("name");
                //获取value
                JSONArray valueArray = itemJson.getJSONArray("value");
                if (valueArray != null && valueArray.size() > 0) {
                    JSONArray valuesA = new JSONArray();
                    for (int j = 0; j < valueArray.size(); j++) {
                        JSONObject valueJson = JSON.parseObject(JSON.toJSONString(valueArray.getJSONObject(j), new SerializerFeature[]{SerializerFeature.WriteMapNullValue}), Feature.OrderedField);
                        for (int o = 0; o < valueJson.keySet().size(); o++) {
                            String key = (String) valueJson.keySet().toArray()[o];
                            if (key.contains("DATE")) {
                                valueJson.put(key,TypeUtils.castToDate(valueArray.getJSONObject(j).getString(key)));
                            }
                        }
                        valueJson.put("AD_CLIENT_ID", clientId);
                        valueJson.put("ID", Tools.getSequence(itemName));
                        valuesA.set(j, valueJson);
                    }

                    StringBuffer itemInsertSql = new StringBuffer();
                    itemInsertSql.append("INSERT INTO " + itemName + "(" + keyAppend(valuesA.getJSONObject(0).keySet()) + ") VALUES(").append(valueAppend(valuesA.getJSONObject(0).size())).append(")");
                    QueryEngine.getInstance().executeBatchUpdate(itemInsertSql.toString(), valuesA);
                }
            }

            JSONObject retailJson = JSON.parseObject(JSON.toJSONString(mainJson, new SerializerFeature[]{SerializerFeature.WriteMapNullValue}), Feature.OrderedField);
            for (int i = 0; i < retailJson.keySet().size(); i++) {
                String key = (String) retailJson.keySet().toArray()[i];
                String value = retailJson.getString(key);
                if(value == null){
                    retailJson.remove(key);
                }else if (value != null && key.contains("DATE")){
                    retailJson.put(key,TypeUtils.castToDate(mainJson.getString(key)));
                }
            }
            retailJson.put("AD_CLIENT_ID", clientId);
            retailJson.put("ID", Tools.getSequence("M_RETAIL"));
            StringBuffer retailInsertSq = new StringBuffer();
            retailInsertSq.append("INSERT INTO M_RETAIL(" + keyAppend(retailJson.keySet()) + ") VALUES(").append(valueAppend(retailJson.size())).append(")");
            QueryEngine.getInstance().executeUpdate(retailInsertSq.toString(), retailJson.values().toArray());
        }
    }

    @Transactional
    public void insertRetail(JSONObject retailJsonObject, String tag){
        String clientIdSql = "SELECT AD_CLIENT_ID FROM OMS_TAG WHERE ISACTIVE='Y' AND TAGNAME = ?";
        JSONObject clientJson = QueryEngine.getInstance().doQueryObject(clientIdSql,new Object[]{tag});
        if (clientJson == null){
            throw new NDSException("公司ID未找到!");
        }
        Long clientId = clientJson.getLong("AD_CLIENT_ID");

        String retailtableName = retailJsonObject.getString("name");
        JSONObject retailValueJson = retailJsonObject.getJSONObject("value");
        JSONArray itemArray = retailJsonObject.getJSONArray("item");

        JSONObject omsRetailJson = JSON.parseObject(JSON.toJSONString(retailValueJson,new SerializerFeature[]{SerializerFeature.WriteMapNullValue}), Feature.OrderedField);
//        omsRetailJson.put("CREATIONDATE",retailJson.getTimestamp("CREATIONDATE"));
//        omsRetSaleJson.put("MODIFIEDDATE",retailJson.getTimestamp("MODIFIEDDATE"));
//        omsRetailJson.put("MODIFIEDDATE",new Timestamp(System.currentTimeMillis()));
        for (int l = 0; l < omsRetailJson.keySet().size(); l++) {
            String key = (String) omsRetailJson.keySet().toArray()[l];
            if (key.contains("DATE") && omsRetailJson.get(key) != null) {
                omsRetailJson.put(key, omsRetailJson.getTimestamp(key));
            }
        }
        omsRetailJson.put("AD_CLIENT_ID",clientId);
        omsRetailJson.put("ID", Tools.getSequence(retailtableName));  //ID

        //生成insertRetSaleSql语句
        StringBuffer insertRetailSql = new StringBuffer( "INSERT INTO "+retailtableName+ "(" );//insertRetSaleSql语句
        StringBuffer q = new StringBuffer();//占位符？
        for (String s:omsRetailJson.keySet()) {
            if(s.equals("ID")){
                q.append( "?" );
                insertRetailSql.append( s +") VALUES(" + q.toString() + ")" );
            }else{
                insertRetailSql.append( s + "," );
                q.append( "?," );
            }
        }
        QueryEngine.getInstance().executeUpdate(insertRetailSql.toString(), omsRetailJson.values().toArray());

        //插子表
        boolean insertItem = false;
        String insertItemSql = null;

        for(int j=0; j<itemArray.size(); j++){
            JSONArray insertItemArray = new JSONArray();

            JSONObject itemJson = itemArray.getJSONObject(j);
            String itemTableName = itemJson.getString("name");
            JSONArray itemValueArray = itemJson.getJSONArray("value");

            for(int k=0; k<itemValueArray.size(); k++){
                JSONObject itemValueJson = itemValueArray.getJSONObject(k);
                JSONObject omsItemJson = JSON.parseObject(JSON.toJSONString(itemValueJson,new SerializerFeature[]{SerializerFeature.WriteMapNullValue}), Feature.OrderedField);
//                omsItemJson.put("CREATIONDATE",itemValueJson.getTimestamp("CREATIONDATE"));
//                omsItemJson.put("MODIFIEDDATE",itemValueJson.getTimestamp("MODIFIEDDATE"));
//                omsItemJson.put("MODIFIEDDATE",new Timestamp(System.currentTimeMillis()));
                for (int l = 0; l < omsItemJson.keySet().size(); l++) {
                    String key = (String) omsItemJson.keySet().toArray()[l];
                    if (key.contains("DATE") && omsItemJson.get(key) != null) {
                        omsItemJson.put(key, omsItemJson.getTimestamp(key));
                    }
                }
                omsItemJson.put("AD_CLIENT_ID",clientId);
                omsItemJson.put("ID", Tools.getSequence(itemTableName));  //ID

                //生成insertItemSql语句
                if(!insertItem) {
                    StringBuffer sb = new StringBuffer( "INSERT INTO "+itemTableName+ "(" );//insertItemSql语句
                    StringBuffer iq = new StringBuffer();//占位符？
                    for (String s:omsItemJson.keySet()) {
                        if(s.equals("ID")){
                            iq.append( "?" );
                            sb.append( s +") VALUES(" + iq.toString() + ")" );
                        }else{
                            sb.append( s + "," );
                            iq.append( "?," );
                        }
                    }
                    insertItemSql = sb.toString();
                    insertItem = true;
                }

                insertItemArray.set(k,omsItemJson);
            }
            if(insertItem){
                QueryEngine.getInstance().executeBatchUpdate(insertItemSql,insertItemArray);//批量插入子表
            }
        }

    }

}
